package com.test.springboot3.springboot3testdemo1.controller;

import com.test.springboot3.springboot3testdemo1.dao.UserRepository;
import com.test.springboot3.springboot3testdemo1.entity.UserMongoEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/8/5-下午7:26
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
@RestController
public class MongoController {
  private static final String COLLECTION_NAME = "javastack";
  private final MongoTemplate mongoTemplate;
  private final UserRepository mongoRepository;

  @GetMapping("/mongo/insert")
  public UserMongoEntity insert(@RequestParam("name") String name) {
    mongoTemplate.dropCollection(COLLECTION_NAME);
    UserMongoEntity user = new UserMongoEntity(100L, name, 1);
    try {
      mongoTemplate.insert(user, COLLECTION_NAME);
    } catch (Exception e) {
      log.error("insert error", e);
    }

    Query query = new Query(Criteria.where("name").is(name));
    return mongoTemplate.findOne(query, UserMongoEntity.class, COLLECTION_NAME);
  }

  @GetMapping("/mongo/repo/insert")
  public UserMongoEntity insertRepo(@RequestParam("name") String name) throws InterruptedException {
    UserMongoEntity user = new UserMongoEntity(100L, name, 1);
    UserMongoEntity userEntity = null;
    try {
      mongoRepository.save(user);
      userEntity = mongoRepository.findByName(name).get(0);
    } catch (Exception e) {
      log.error("insert error", e);
    }

    return userEntity;
  }
}
